<template>
  <div class="app-container delivery-reports">
    <!-- 筛选条件区 -->
    <el-card class="filter-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-s-data"></i> 筛选条件</span>
        <div class="header-tip">
          <i class="el-icon-info"></i> 导出功能将下载选择月份的送货单明细数据
        </div>
      </div>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="统计月份" prop="month">
          <el-date-picker
            v-model="queryParams.month"
            type="month"
            placeholder="选择月份"
            value-format="yyyy-MM"
            style="width: 180px"
            @change="handleQuery"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="统计指标" prop="metric">
          <el-select 
            v-model="queryParams.metric" 
            placeholder="请选择统计指标" 
            style="width: 180px"
            @change="handleQuery"
          >
            <el-option label="总金额" value="totalAmount" />
            <el-option label="送货单数" value="deliveryCount" />
            <el-option label="明细行数" value="detailCount" />
            <el-option label="总数量" value="totalQuantity" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="success" icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading" :title="getExportTooltip()">导出数据</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 上方三个小报表区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 第一个小报表 - 送货单趋势 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="chart-header">
            <span><i class="el-icon-s-marketing"></i> 总体指标</span>
          </div>
          <div class="chart-content">
            <div class="summary-metrics">
              <div class="main-metric">
                <div class="metric-value">{{ getCurrentMetricValue() }}</div>
                <div class="metric-label">{{ metricInfo.label }}({{ metricInfo.unit }})</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 第二个小报表 - 物料分布 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="chart-header">
            <span><i class="el-icon-pie-chart"></i> 客户分布环形图</span>
          </div>
          <div class="chart-content">
            <div ref="distributionChart" class="chart-container"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 第三个小报表 - 金额统计 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="chart-header">
            <span><i class="el-icon-money"></i> 产品分布图</span>
          </div>
          <div class="chart-content">
            <div ref="amountChart" class="chart-container"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 下方横贯大报表区域 -->
    <el-card class="main-chart-card" shadow="hover">
      <div slot="header" class="chart-header">
        <span><i class="el-icon-s-data"></i> 配送趋势图</span>
      </div>
      <div class="main-chart-content">
        <div ref="mainChart" class="main-chart-container"></div>
      </div>
    </el-card>

   
  </div>
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { getDashboardData } from '@/api/test/deliveryReports'

export default {
  name: "DeliveryReports",
  data() {
    return {
      // 查询参数
      queryParams: {
        month: this.getCurrentMonth(),
        metric: 'totalAmount'
      },
      // 图表实例
      distributionChart: null,
      amountChart: null,
      mainChart: null,
      // 数据对话框
      dataDialogVisible: false,
    
      // 总体指标数据
      summaryData: {
        totalAmount: '0.00'
      },
      // 当前指标信息
      metricInfo: {
        label: '总金额',
        unit: '元',
        formatter: 'currency'
      },
      // 客户数据
      customerData: [],
      currentHighlightIndex: 0,
      customerRotationTimer: null,
      // 产品数据
      productData: [],
      // 趋势数据
      trendData: [],
      // 加载状态
      loading: false,
      // 导出加载状态
      exportLoading: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
      this.loadData()
    })
  },
  beforeDestroy() {
    this.destroyCharts()
  },
  methods: {
    // 获取当前月份
    getCurrentMonth() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      return `${year}-${month}`
    },
    
    // 初始化所有图表
    initCharts() {
      this.$nextTick(() => {
        this.initDistributionChart()
        this.initAmountChart()
        this.initMainChart()
      })
    },
    

    
    // 初始化分布图表
    initDistributionChart() {
      this.distributionChart = echarts.init(this.$refs.distributionChart, 'macarons')
      
      // 初始化空数据，等待API加载
      this.customerData = []
      this.currentHighlightIndex = 0
      
      // 如果有数据，则更新图表，否则显示空图表
      if (this.customerData.length > 0) {
        this.updateDistributionChart()
        this.startCustomerRotation()
      }
    },
    
    // 更新客户分布环形图
    updateDistributionChart() {
      if (!this.customerData || this.customerData.length === 0) {
        return
      }
      
      const data = this.customerData.map((item, index) => ({
        ...item,
        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }))
      
      const currentCustomer = this.customerData[this.currentHighlightIndex] || {
        name: '暂无数据',
        value: 0,
        percentage: 0
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            const unit = this.metricInfo.unit || ''
            const value = this.formatValue(params.value, this.metricInfo.formatter)
            return `${this.metricInfo.label} <br/>${params.name}: ${value}${unit} (${params.percent}%)`
          }
        },
        graphic: [
           {
             type: 'text',
             left: 'center',
             top: '40%',
             transition: ['style'],
             enterFrom: {
               style: {
                 opacity: 0,
                 scaleX: 0.5,
                 scaleY: 0.5
               }
             },
             style: {
               text: currentCustomer.name,
               fontSize: 16,
               fontWeight: 'bold',
               fill: '#333',
               textAlign: 'center',
               opacity: 1,
               scaleX: 1,
               scaleY: 1
             }
           },
           {
             type: 'text',
             left: 'center',
             top: '50%',
             transition: ['style'],
             enterFrom: {
               style: {
                 opacity: 0,
                 scaleX: 0.5,
                 scaleY: 0.5
               }
             },
             style: {
               text: this.formatCustomerValue(currentCustomer.value),
               fontSize: 20,
               fontWeight: 'bold',
               fill: '#409eff',
               textAlign: 'center',
               y: 25,
               opacity: 1,
               scaleX: 1,
               scaleY: 1
             }
           },
           {
             type: 'text',
             left: 'center',
             top: '60%',
             transition: ['style'],
             enterFrom: {
               style: {
                 opacity: 0,
                 scaleX: 0.5,
                 scaleY: 0.5
               }
             },
             style: {
               text: `占比: ${currentCustomer.percentage}%`,
               fontSize: 12,
               fill: '#666',
               textAlign: 'center',
               opacity: 1,
               scaleX: 1,
               scaleY: 1
             }
           }
         ],
        series: [{
          name: `客户${this.metricInfo.label}`,
          type: 'pie',
          radius: ['40%', '70%'], // 内外半径，形成环形
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          animationType: 'scale',
          animationEasing: 'elasticOut',
          animationDelay: function (idx) {
            return Math.random() * 200
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: false
            },
            itemStyle: {
              shadowBlur: 20,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
              borderWidth: 3,
              borderColor: '#fff'
            }
          },
          labelLine: {
            show: false
          },
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2
          },
          data: data
        }]
      }
      
      this.distributionChart.setOption(option)
      
      // 添加鼠标事件监听
      this.distributionChart.off('mouseover')
      this.distributionChart.off('mouseout')
      
      this.distributionChart.on('mouseover', (params) => {
        if (params.componentType === 'series') {
          this.stopCustomerRotation()
          this.currentHighlightIndex = params.dataIndex
          this.updateDistributionChart()
        }
      })
      
      this.distributionChart.on('mouseout', () => {
        this.startCustomerRotation()
      })
      
      // 高亮当前项
      this.distributionChart.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: this.currentHighlightIndex
      })
    },
    
    // 开始客户轮换
    startCustomerRotation() {
      if (this.customerRotationTimer) {
        clearInterval(this.customerRotationTimer)
      }
      
      this.customerRotationTimer = setInterval(() => {
        // 取消之前的高亮
        this.distributionChart.dispatchAction({
          type: 'downplay',
          seriesIndex: 0,
          dataIndex: this.currentHighlightIndex
        })
        
        // 切换到下一个客户
        this.currentHighlightIndex = (this.currentHighlightIndex + 1) % this.customerData.length
        
        // 更新图表
        this.updateDistributionChart()
      }, 3000) // 每3秒切换一次
    },
    
    // 停止客户轮换
    stopCustomerRotation() {
      if (this.customerRotationTimer) {
        clearInterval(this.customerRotationTimer)
        this.customerRotationTimer = null
      }
    },
    
    // 初始化产品销售图表
    initAmountChart() {
      this.amountChart = echarts.init(this.$refs.amountChart, 'macarons')
      
      // 初始化空数据，等待API加载
      this.productData = []
      
      // 如果有数据，则更新图表
      if (this.productData.length > 0) {
        this.updateProductChart()
      }
    },
    
    // 更新产品销售图表
    updateProductChart() {
      if (!this.productData || this.productData.length === 0) {
        return
      }
      
      const yAxisData = this.productData.map(item => item.code)
      const seriesData = this.productData.map(item => item.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            const data = params[0]
            const productInfo = this.productData[data.dataIndex]
            const unit = this.metricInfo.unit || ''
            const value = this.formatValue(data.value, this.metricInfo.formatter)
            return `${productInfo.code} - ${productInfo.name}<br/>${this.metricInfo.label}: ${value}${unit}`
          }
        },
        grid: {
          left: '15%',
          right: '10%',
          bottom: '10%',
          top: '5%',
          containLabel: false
        },
        xAxis: {
          type: 'value',
          show: false, // 隐藏横坐标
          splitLine: {
            show: false // 隐藏分割线
          }
        },
        yAxis: {
          type: 'category',
          data: yAxisData,
          axisLabel: {
            fontSize: 11,
            color: '#666',
            interval: 0,
            lineHeight: 14
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          }
        },
        series: [{
          name: this.metricInfo.label,
          type: 'bar',
          data: seriesData,
          barWidth: '60%',
          itemStyle: {
            borderRadius: [0, 4, 4, 0],
            color: function(params) {
              // 根据数值大小使用不同的渐变色
              const colors = [
                ['#ff7875', '#ff4d4f'], // 红色渐变
                ['#ffa940', '#fa8c16'], // 橙色渐变
                ['#52c41a', '#389e0d'], // 绿色渐变
                ['#1890ff', '#096dd9'], // 蓝色渐变
                ['#722ed1', '#531dab']  // 紫色渐变
              ]
              const colorPair = colors[params.dataIndex % colors.length]
              return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: colorPair[0] },
                { offset: 1, color: colorPair[1] }
              ])
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
          },
          label: {
            show: true,
            position: 'right',
            formatter: (params) => {
              if (this.metricInfo.formatter === 'currency') {
                return `¥${(params.value / 10000).toFixed(1)}万`
              } else {
                return this.formatNumber(params.value)
              }
            },
            color: '#666',
            fontSize: 11
          },
          animationDelay: function (idx) {
            return idx * 100
          }
        }]
      }
      
      this.amountChart.setOption(option)
    },
    
    // 初始化主图表
    initMainChart() {
      this.mainChart = echarts.init(this.$refs.mainChart, 'macarons')
      this.updateMainChart()
    },
    
    // 更新主图表
    updateMainChart() {
      // 使用真实趋势数据或生成模拟数据
      let xAxisData = []
      let seriesData = []
      
      if (this.trendData && this.trendData.length > 0) {
        // 使用真实数据
        xAxisData = this.trendData.map(item => item.dateLabel)
        if (this.metricInfo.formatter === 'currency') {
          seriesData = this.trendData.map(item => Math.round(item[this.queryParams.metric] / 10000)) // 转为万元
        } else {
          seriesData = this.trendData.map(item => item[this.queryParams.metric] || 0)
        }
      } else {
        // 使用模拟数据
        xAxisData = ['1日', '5日', '10日', '15日', '20日', '25日', '30日']
        const baseData = [150, 232, 201, 154, 190, 330, 410]
        seriesData = baseData.map(value => 
          value + Math.floor(Math.random() * 100) - 50
        )
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const data = params[0]
            let valueText = ''
            if (this.metricInfo.formatter === 'currency') {
              valueText = `¥${data.value}万`
            } else {
              valueText = `${data.value}${this.metricInfo.unit}`
            }
            return `${data.axisValue}<br/>${this.metricInfo.label}: ${valueText}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData,
          axisLabel: {
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#e0e0e0'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#666',
            formatter: (value) => {
              if (this.metricInfo.formatter === 'currency') {
                return `${value}万`
              } else {
                return value.toString()
              }
            }
          },
          axisLine: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0'
            }
          }
        },
        series: [
          {
            name: this.metricInfo.label,
            type: 'line',
            smooth: false,
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(64, 158, 255, 0.3)'
                }, {
                  offset: 1, color: 'rgba(64, 158, 255, 0.05)'
                }]
              }
            },
            lineStyle: {
              color: '#409eff',
              width: 3
            },
            itemStyle: {
              color: '#409eff',
              borderColor: '#fff',
              borderWidth: 2
            },
            data: seriesData
          }
        ]
      }
      this.mainChart.setOption(option)
    },
    
    // 销毁图表
    destroyCharts() {
      // 停止客户轮换定时器
      this.stopCustomerRotation()
      
      if (this.distributionChart) {
        this.distributionChart.dispose()
        this.distributionChart = null
      }
      if (this.amountChart) {
        this.amountChart.dispose()
        this.amountChart = null
      }
      if (this.mainChart) {
        this.mainChart.dispose()
        this.mainChart = null
      }
    },
    
    // 查询数据
    handleQuery() {
      this.loadData()
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams = {
        month: this.getCurrentMonth(),
        metric: 'totalAmount'
      }
      this.loadData()
    },
    
    // 加载数据
    loadData() {
      this.loading = true
      
      // 调用API获取数据
      getDashboardData({
        month: this.queryParams.month,
        metric: this.queryParams.metric || 'totalAmount'
      }).then(response => {
        const data = response.data
        
        // 更新总体指标数据和指标信息
        if (data.summary) {
          this.summaryData = data.summary
        }
        if (data.metricInfo) {
          this.metricInfo = data.metricInfo
        }
        
        // 更新客户数据
        if (data.customerStats && data.customerStats.length > 0) {
          this.customerData = data.customerStats.map(customer => ({
            value: parseFloat(customer[this.queryParams.metric]) || 0,
            name: customer.customerName || customer.customerCode || '未知客户',
            percentage: parseFloat(customer.percentage) || 0,
            rawData: customer // 保存原始数据以便后续使用
          }))
          
          if (this.customerData.length > 0) {
            this.currentHighlightIndex = 0
            this.updateDistributionChart()
            this.startCustomerRotation()
          }
        }
        
        // 更新产品数据
        if (data.productStats && data.productStats.length > 0) {
          this.productData = data.productStats.map(product => ({
            code: product.materialCode || 'P000',
            name: product.materialName || '未知产品',
            value: parseFloat(product[this.queryParams.metric]) || 0,
            rawData: product // 保存原始数据以便后续使用
          }))
          
          // 后端已经按用户选择的指标正确降序排序
          // 条形图从下往上显示，所以需要反转数组让最大值显示在顶部
          this.productData.reverse()
          
          this.updateProductChart()
        }
        
        // 更新趋势数据并刷新主图表
        if (data.trendStats && data.trendStats.length > 0) {
          this.trendData = data.trendStats
          this.updateMainChart()
        }
        
        this.loading = false
      }).catch(error => {
        console.error('加载数据失败:', error)
        this.$message.error('数据加载失败，请稍后重试')
        this.loading = false
        
        // 如果API调用失败，保持现有的模拟数据不变
        // 这样用户界面仍然可以正常显示
      })
    },
    
    // 导出数据
    handleExport() {
      // 确认对话框
      const exportMessage = this.queryParams.month 
        ? `确定要导出${this.queryParams.month}月份的送货单数据吗？`
        : '确定要导出全部送货单数据吗？'
      
      this.$modal.confirm(exportMessage).then(() => {
        this.doExport()
      }).catch(() => {
        // 用户取消，不做任何操作
      })
    },
    
    // 执行导出
    doExport() {
      this.exportLoading = true
      
      try {
        // 构造导出查询参数
        const exportParams = {}
        
        // 如果选择了月份，设置日期范围
        if (this.queryParams.month) {
          const year = this.queryParams.month.split('-')[0]
          const month = this.queryParams.month.split('-')[1]
          // 计算月份的第一天和最后一天
          const firstDay = `${year}-${month}-01`
          const lastDay = new Date(parseInt(year), parseInt(month), 0).getDate()
          const lastDayStr = `${year}-${month}-${String(lastDay).padStart(2, '0')}`
          
          exportParams.params = {
            beginDeliveryDate: firstDay,
            endDeliveryDate: lastDayStr
          }
        }
        
        // 生成文件名
        const fileName = this.queryParams.month 
          ? `delivery_report_${this.queryParams.month.replace('-', '')}_${new Date().getTime()}.xlsx`
          : `delivery_report_all_${new Date().getTime()}.xlsx`
        
        // 调用导出接口
        this.download('test/delivery/export', exportParams, fileName)
        
        this.$message.success('导出请求已发送，请稍候下载...')
        
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败：' + (error.message || '未知错误'))
      } finally {
        // 延迟关闭loading状态，给用户反馈时间
        setTimeout(() => {
          this.exportLoading = false
        }, 2000)
      }
    },
    
    // 格式化货币显示
    formatCurrency(amount) {
      if (amount == null || amount === '') {
        return '0.00'
      }
      return parseFloat(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },
    
    // 格式化数字显示
    formatNumber(number) {
      if (number == null || number === '') {
        return '0'
      }
      return parseFloat(number).toLocaleString('zh-CN')
    },
    
    // 根据格式化类型显示数值
    formatValue(value, formatter) {
      if (formatter === 'currency') {
        return this.formatCurrency(value)
      } else {
        return this.formatNumber(value)
      }
    },
    
    // 获取当前指标的值
    getCurrentMetricValue() {
      if (!this.summaryData || !this.queryParams.metric) {
        return '0'
      }
      const value = this.summaryData[this.queryParams.metric] || 0
      return this.formatValue(value, this.metricInfo.formatter)
    },
    
    // 格式化客户图表中心显示的值
    formatCustomerValue(value) {
      if (this.metricInfo.formatter === 'currency') {
        return `¥${(value / 10000).toFixed(1)}万`
      } else {
        return this.formatNumber(value)
      }
    },
    
    // 获取导出按钮提示信息
    getExportTooltip() {
      if (this.queryParams.month) {
        return `导出${this.queryParams.month}月份的送货单数据`
      } else {
        return '导出全部送货单数据'
      }
    },
    
    // 关闭对话框
    handleClose() {
      this.dataDialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.delivery-reports {
  .filter-card {
    margin-bottom: 20px;
    
    .header-tip {
      float: right;
      font-size: 12px;
      color: #909399;
      line-height: 20px;
      
      i {
        margin-right: 4px;
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
  }
  
  .chart-card {
    height: 350px;
    
    .chart-header {
      display: flex;
      align-items: center;
    }
    
    .chart-content {
      height: 280px;
      
      .chart-container {
        width: 100%;
        height: 100%;
      }
      
      .summary-metrics {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100%;
        padding: 30px 20px;
        position: relative;
        
        .main-metric {
          text-align: center;
          
          .metric-value {
            font-size: 48px;
            font-weight: 600;
            color: #409eff;
            margin-bottom: 8px;
            letter-spacing: 1px;
            text-shadow: 0 2px 4px rgba(64, 158, 255, 0.1);
          }
          
          .metric-label {
            font-size: 16px;
            color: #909399;
            font-weight: 500;
          }
        }
        
        // 添加装饰性背景
        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 60px;
          height: 4px;
          background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
          border-radius: 2px;
        }
      }
    }
  }
  
  .main-chart-card {
    .chart-header {
      display: flex;
      align-items: center;
    }
    
    .main-chart-content {
      height: 320px;
      
      .main-chart-container {
        width: 100%;
        height: 100%;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .delivery-reports {
    .filter-card {
      .header-tip {
        float: none;
        clear: both;
        margin-top: 8px;
        text-align: left;
      }
    }
    
    .chart-card {
      margin-bottom: 20px;
    }
    
    .chart-header {
      flex-direction: column;
      align-items: flex-start !important;
    }
  }
}
</style> 